package android.gsn.engine.utility;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import test.gsn.portal.V2PlayPortalActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.gsn.dataCommon.UserData;
import com.gsn.engine.utility.IUtility;

public class UtilityAndroid implements IUtility {
	private static final String tag = "Utility Android";
	private Activity activity;
	// public EditText arrayEditText[];
	public Map<String, EditText> arrayEditText;

	public UtilityAndroid() {
		arrayEditText = new HashMap<String, EditText>();
	}

	@Override
	public void setActivity(Object activity) {
		this.activity = (Activity) activity;
	}

	private ProgressDialog progressDialog;

	@Override
	public void showProgressDialog(final String title, final String msg) {
		Gdx.app.log(tag, "show Dialog");
		if (activity == null)
			return;
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (progressDialog != null)
					progressDialog.dismiss();
				progressDialog = ProgressDialog.show(activity, title, msg, true);
			}
		});

	}

	@Override
	public void hideProgressDialog() {
		if (activity == null)
			return;
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Gdx.app.log(tag, "hide Dialog");
				progressDialog.hide();
				progressDialog.dismiss();
			}
		});
	}

	@Override
	public void runOnUiThread(Runnable method) {
		activity.runOnUiThread(method);
	}

	@Override
	public void downloadPictureAsync(final String id, final String link, final int width, final int height, final String localPath, final IPictureDownloadListener listener) {
		final int quality = 80;
		File tmp;
		if (activity == null)
			return;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
			tmp = activity.getExternalCacheDir();
		else
			tmp = activity.getCacheDir();
		final File cacheDir = tmp;

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {

				URL url;
				URLConnection uCon;
				Bitmap bMap;
				Bitmap des;
				try {
					File fileOut = new File(cacheDir, localPath);
					if (fileOut.exists()) {
						Log.i(tag, "Da ton tai anh!! Ko phai down lai");
						listener.onFinishLoading(id, fileOut);
						return;
					}
					if (link != null && link.equals(""))
						return;
					url = new URL(link);
					uCon = url.openConnection();
					bMap = BitmapFactory.decodeStream(uCon.getInputStream());
					des = Bitmap.createScaledBitmap(bMap, width, height, true);
					OutputStream out = new FileOutputStream(fileOut);

					des.compress(Bitmap.CompressFormat.PNG, quality, out);
					out.flush();
					out.close();
					listener.onFinishLoading(id, fileOut);
					Log.i(tag, "Down anh vao : " + fileOut.getAbsolutePath());
				} catch (Exception e) {
					Log.e("Gallery", "loi gi nay", e);
					listener.onError(e);
				}
			}
		});
		t.start();

	}

	@Override
	public void toast(final String toast, boolean shortTime) {
		if (activity == null)
			return;
		final int length = shortTime ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG;
		Gdx.app.log(tag, "toast : " + toast);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(activity, toast, length).show();
			}
		});

	}

	private IInputText inputTextListener;

	@Override
	public void showInputTextDlg(String inText, String outDefaultText, IInputText listener) {
		this.inputTextListener = listener;
	}

	@Override
	public void makeTextFieldWithScreenCoordinate(Stage stage, TextField.TextFieldStyle style, String type, String content, float width, float height, float marginTop, float marginLeft) {
		// TODO Auto-generated method stub

		// arrayEditText[type] = new TextEditLogic(content, true, (int) width,
		// (int) height, (int) marginLeft, (int) marginTop);
		if (activity == null)
			return;
		arrayEditText.put(type, ((V2PlayPortalActivity) activity).makeTextField(type, content, width, height, marginTop, marginLeft));
	}

	@Override
	public void hideTextField(String type) {
		// TODO Auto-generated method stub
		if (activity == null)
			return;
		((V2PlayPortalActivity) activity).hideTextField(type);
		// arrayEditText[type].setVisibility(View.INVISIBLE);
		// if (activity != null)
		// ((V2PlayPortalActivity) activity).hideTextField(type);
	}

	@Override
	public String getString(String type) {
		// TODO Auto-generated method stub
		if (activity == null)
			return "";
		return arrayEditText.get(type).getText().toString();
	}

	@Override
	public void setTextField(String type, String content) {
		// TODO Auto-generated method stub
		if (activity == null)
			return;
		((V2PlayPortalActivity) activity).setTextField(type, content);
	}

	@Override
	public void visibleTextField(String type) {
		// TODO Auto-generated method stub
		if (activity == null)
			return;
		((V2PlayPortalActivity) activity).visibleTextField(type);

	}

	public void load() {
		SharedPreferences shareData = activity.getSharedPreferences("portal", 0);
		UserData.name = shareData.getString(UserData.NAME, "");
		UserData.passWord = shareData.getString(UserData.PASSWORD, "");
		UserData.save = shareData.getBoolean(UserData.SAVE_PASS, false);
		UserData.sessionKey = shareData.getString(UserData.SESSION_KEY, "");
		UserData.sound = shareData.getBoolean(UserData.SOUND, true);
		UserData.music = shareData.getBoolean(UserData.MUSIC, true);
		UserData.vibrate = shareData.getBoolean(UserData.VIBRATE, true);
	}

	public void save() {
		SharedPreferences shareData = activity.getSharedPreferences("portal", 0);
		SharedPreferences.Editor editor = shareData.edit();
		editor.putString(UserData.NAME, UserData.name);
		editor.putString(UserData.PASSWORD, UserData.passWord);
		editor.putBoolean(UserData.SAVE_PASS, UserData.save);
		editor.putString(UserData.SESSION_KEY, UserData.sessionKey);
		editor.commit();
	}

	public void remove() {
		SharedPreferences shareData = activity.getSharedPreferences("portal", 0);
		SharedPreferences.Editor editor = shareData.edit();
		editor.remove(UserData.SAVE_PASS);
		editor.remove(UserData.NAME);
		editor.remove(UserData.PASSWORD);
		editor.remove(UserData.SESSION_KEY);
		editor.commit();
	}

	public void saveSetting() {
		SharedPreferences shareData = activity.getSharedPreferences("portal", 0);
		SharedPreferences.Editor editor = shareData.edit();
		editor.putBoolean(UserData.SOUND, UserData.sound);
		editor.putBoolean(UserData.MUSIC, UserData.music);
		editor.putBoolean(UserData.VIBRATE, UserData.vibrate);

		editor.commit();
	}

	@Override
	public void toastException(String msg, Exception ex) {
		if (activity == null)
			return;
		toast("msg " + ex.getMessage(), false);
	}

	@Override
	public void inviteFriend() {
		// TODO Auto-generated method stub
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Uri smsToUri = Uri.parse("smsto:");
				Intent returnIt = new Intent(Intent.ACTION_SENDTO, smsToUri);
				returnIt.putExtra("sms_body", "Tải myPlay về chơi cùng với tui đi, vui lắm đó!");
				returnIt.putExtra("exit_on_sent", true);
				activity.startActivity(returnIt);
			}
		});
	}

	@Override
	public void register() {
		// TODO Auto-generated method stub
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Intent shareOnTwitterIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://id.me.zing.vn/fs/register"));
				activity.startActivity(shareOnTwitterIntent);
			}
		});
	}

	@Override
	public void endActivity() {
		// TODO Auto-generated method stub
		if (activity == null)
			return;
		((V2PlayPortalActivity) activity).endGame();
	}

}
